<?php
class UsersController extends CmsUsersController
{
	var $name = 'users';
	var $indexMethods = array();
	
	function beforeFilter()
	{
		parent::beforeFilter();
		$this->indexMethods = cr('indexMethods.Users');
		$this->Auth->loginRedirect = array('action'=>'profile');
	}
	function admin_toggleEditor($id = null)
	{
		$user = $this->User->find('first',array('conditions'=>array('User.id'=>$id),'recursive'=>-1));
		if(empty($user))
		{
			$this->errorMsg();
			$this->redirect($this->referer());
			
		}
		$editorStatus = $user['User']['is_editor'];
		if($editorStatus == User::ACTIVATED_EDITOR)
		{
			$newStatus = User::DEACTIVATED_EDITOR;
			$successMsg = 'User has been degraded.'; 
			$errorMsg = 'User could not be degraded.';
		}else
		{
			$successMsg = 'User has been upgraded to editor.'; 
			$errorMsg = 'User could not be upgraded to editor.';
			$newStatus = User::ACTIVATED_EDITOR;
		}
		$this->User->id = $id;
		if($this->User->saveField('is_editor',$newStatus))
		{
			$this->successMsg(__($successMsg));
		}else
		{
			$this->errorMsg(__($errorMsg));
		}
		$this->redirect($this->referer());
	}
	
	function index($type = false)
	{
		$this->User->setScope('activated');
		$this->pageTitle = __('Users');	
		$this->paginate['recursive'] = -1;
		$this->paginate['order'] = array('User.created DESC');
		if($type)
		{
			if(in_array($type, array_keys($this->indexMethods)))
			{
				$subMethodName = $this->indexMethods[$type]['method'];
				if(isset($this->indexMethods[$type]['title']))
				{
					$this->pageTitle = __($this->indexMethods[$type]['title']);
				}
				$this->{$subMethodName}();
			}
			else
			{
				$this->errorMsg(__("Invalid URL"));
				$this->redirect("/");
			}
		}
		$users = $this->paginate();	
		if($this->_isVarRequest())
		{
			return $users;
		}	
		$this->set(compact('users'));
	}
	
	function __topReviewers()
	{
		$this->paginate['order'] = array('review_count DESC');		
	}
	function notification()
	{
		$this->pageTitle = __("Notification");
		$authedUser = $this->Session->read('Auth.User');
		$this->User->recursive = -1;
		$userData = $this->User->findById($authedUser['id']);
		
		if(!empty($this->data))
		{
			$this->data['User']['id'] = $authedUser['id'];
			if($this->User->save($this->data))
			{
				$this->successMsg(__("Notifications has been updated successfully."));
				$this->redirect(array('controller'=>'users','action'=>'profile'));
			}else
			{
				$this->errorMsg(__("Sorry, notifications could not be updated."));
			}			
		}	
		$this->data = $userData;		
	}
	
	function profile($slug = null)
	{
		$this->actionId = 'profilepages';
		
		if(empty($slug))
		{
			$slug = $this->Session->read('Auth.User.slug');
		}
		$this->User->recursive = -1;
		$user = $this->User->findBySlug($slug);
		if(empty($user))
		{
			$this->errorMsg(__('Invalid URL'));
			$this->redirect('/');			
		}
		if($user['User']['id'] == $this->Session->read('Auth.User.id'))
		{
			$this->pageTitle = __("My Profile");
		}else
		{
			$this->pageTitle = sprintf(__("Profile of %s"),$user['User']['username']);	
		}
		$favListingIds = cri('Users.UserFavorite')->find('list',array('fields'=>array('item_id'),'conditions'=>array('user_id'=>$user['User']['id'],'type'=>'Listing')));
		$favListingCount = $this->User->Listing->find('count',array('conditions'=>array('Listing.id'=>$favListingIds,'Listing.status'=>Listing::PUBLISH)));
		$user['User']['fav_listing_count'] = $favListingCount;
		$allowReviewComment = cr('ReviewConfig.allow_comment');
		$this->set(compact('user','allowReviewComment'));
		$defaultFields = $this->User->getFields('group','admin_view');
		$this->set('defaultFields',$defaultFields);
		$this->set('fieldPropertiesObj',$this->User->getAttributes());
		$this->Set('userModel',$this->User);	
	}
	
	function admin_index()
	{
		$this->paginate['limit'] = 10;
		parent::admin_index();
		$this->pageTitle= __("Users");
	}
	
	function admin_view($id = null)
	{
		$this->pageTitle = __('View');
		$this->User->recursive = -1;
		$user = $this->User->findById($id);
		if(empty($user))
		{
			$this->errorMsg(__('Invalid User.', true));
			$this->redirect($this->referer());
		}
		
		$defaultFields = $this->User->getFields('group','admin_view');
		$this->set('user',$user);
		$this->set('fieldPropertiesObj',$this->User->getAttributes());
		$this->set('defaultFields',$defaultFields);
		$this->Set('userModel',$this->User);		
	}
	
	function admin_search()
	{
		if($this->referer() == '/')
		{
			$this->redirect('/admin/users/index');	
		}
		$default = array(
			'username'=>'',
			'type'=>'',
		);
		$params = am($default,$this->data['User']);
		
		if(!empty($params['username']))
		{
			$this->paginate['conditions']['AND'][] = array('User.username LIKE'=>'%'.$params['username'].'%');	
		}
		
		if(!empty($params['type']))
		{
			if($params['type'] == 'editor')
			{
				$this->paginate['conditions']['AND'][] = array('User.is_editor'=>1);
			}else
			{
				$this->paginate['conditions']['AND'][] = array('not'=>array('User.is_editor'=>1));
			}	
		}
		
		$this->pageTitle = __("Search Result");
		$this->paginate['limit'] = 10;
		if(isset($this->params['named']['page']) || isset($this->params['named']['limit']))
		{
			$this->paginate['conditions'] = $this->Session->read('conditions');
		}elseif(isset($this->paginate['conditions']))
		{
			$this->Session->write('conditions',$this->paginate['conditions']);
		}
		$userData = $this->paginate();		
		$this->set('users',$userData);
		$this->render('admin_index');
	}
	
	function admin_edit($id = null) 
	{
		$this->_getUserModel()->recursive = -1;
		$customFields = $this->User->getFields('group','edit');
		parent::admin_edit($id);
		$this->pageTitle = __('Edit');
		$this->set('customFields',$customFields);
	}
	
	function register()
	{ 
		if(cr("Users.noRegister") == true)
		{
			$this->redirect(array("action"=>"login"));
			return;
		}
		$this->actionId = "user_register";
		parent::register();
	}
    
    /**
     * Overwritten for cms users to allow custom changes.
     */
    function editProfile()
	{
		$this->pageTitle = __('Edit Profile');
		$authedUser = $this->Session->read('Auth.'.$this->userModelAlias);
        $this->_getUserModel()->recursive = -1;  
		if (!empty($this->data))
		{
			$this->data[$this->userModelAlias]['id']=$authedUser['id'];
			if ($this->_getUserModel()->save($this->data))
			{
				callHooks('AfterEditProfile','.+',$this);
                $userInfo = $this->_getUserModel()->findById($authedUser['id']);
                //update session data.
                $sessionUser = $this->Session->read("Auth.User");
                $this->Session->write("Auth.User",am($sessionUser,$userInfo['User']));
				$this->successMsg(__("Your profile has been updated."));
				$url = array('controller'=>'users','action'=>'profile','plugin'=>'users');
                if(isset($_GET['backTo']))
                {
                  $url = $_GET['backTo'];
                }
                $this->redirect($url);
			} 
			else
			{
				$this->errorMsg(__("Unable to update your profile."));
			}
		}
		else
		{
			$this->data = $this->_getUserModel()->findById($authedUser['id']);
		}
        $buniessInfo = false;
        if(AppUtility::allowPaidListing())
        {
           $ListingModel = cri("Listing");
           if(isset($this->params['named']['buniessInfo']))
           {
             $buniessInfo = true;
           }else if($ListingModel->hasAny(array("owner_id"=>$authedUser['id'])))
           {
             $buniessInfo = true;
           }
        }
        $this->set("buniessInfo",$buniessInfo);
	}
}
?>